package org.example.service.impl;

import io.jsonwebtoken.Claims;
import org.example.config.JwtConfig;
import org.example.service.SeckillService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class SeckillServiceImpl implements SeckillService {
    private StringRedisTemplate stringRedisTemplate;
    //秒杀开始时间
    private Date data=new Date(124,9,27,11,41,30);
    private String bookId="1521444078216750661";
    private String money="81.6";

    @Autowired
    public SeckillServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        ListOperations<String, String> list = stringRedisTemplate.opsForList();
        //清理原来内容
        stringRedisTemplate.delete("SEC_KILL_LIST");
        stringRedisTemplate.delete("SECKILL");
        //初始化秒杀商品名单
        list.rightPush("SEC_KILL_LIST", bookId);
        list.rightPush("SEC_KILL_LIST", bookId);
        list.rightPush("SEC_KILL_LIST", bookId);

    }
    @Override
    public JsonResult seckill(String token) {
        HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
        ListOperations<String, String> list = stringRedisTemplate.opsForList();
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        //验证判断
        //1.必须在秒杀开始之后
        Date nowdate = new Date();
        if (nowdate.before(data)){
            return ResultTool.fail(5009,"秒杀还没有开始");
        }
        // 2. 单个用户只能秒杀该商品一次
        Object val = hash.get("SECKILL", userId);
        if (val != null){
            return ResultTool.fail(5008,"一次只能秒杀一件商品");
        }
        // 3. 秒杀结束 卖完了
        Long size = list.size("SEC_KILL_LIST");
        System.out.println(size);
        if (size==null||size == 0){
            return ResultTool.fail(5007,"秒杀已经结束");
        }
        //秒杀
        stringRedisTemplate.watch("SEC_KILL_LIST");
        SessionCallback<List<Object>> sessionCallback = new SessionCallback<List<Object>>(){
            @Override
            public <K,V> List<Object> execute(RedisOperations<K,V> operations) throws DataAccessException {
                stringRedisTemplate.multi();
                // 1. 记录名单
                hash.put("SECKILL",userId,"1");
                // 2. 减少库存
                list.rightPop("SEC_KILL_LIST");
                return stringRedisTemplate.exec();
            }
        };
        List<Object> exec = stringRedisTemplate.execute(sessionCallback);
        if (exec.size()==0||exec.get(0)==null){
            return ResultTool.fail(5006,"秒杀失败");
        }
        JsonResult success = ResultTool.success(bookId);
        success.setError(money);
        return success;
    }
}
